/*
 * @Author: 高瑞寒 15932717091@163.com
 * @Date: 2022-01-23 14:45:23
 * @LastEditTime: 2022-05-14 02:10:29
 * @LastEditors: 高瑞寒 15932717091@163.com
 * @Description:
 */

// token
//
import axios from 'axios'
import store from '@/store'
import { ElMessage } from 'element-plus'
import { isCheckTimeStamp } from './auth'
// 实例
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    config.headers.icode = '39DB7A17AC913DD7'
    config.headers['Accept-Language'] = store.getters.language
    if (store.getters.token) {
      if (isCheckTimeStamp()) {
        store.dispatch('user/logout')
        return Promise.reject(new Error('token 失效'))
      }
      // 如果token存在 注入token
      config.headers.Authorization = `Bearer ${store.getters.token}`
    }
    return config
  }
)
// 响应拦截器
service.interceptors.response.use(
  async response => {
    const { success, message, data } = response.data
    if (success) {
      return data
    } else {
      ElMessage.error(message)
      return Promise.reject(new Error(message))
    }
  },
  error => {
    if (error.response &&
      error.response.data &&
      error.response.data.code === 401) {
      store.dispatch('user/logout')
    }
    ElMessage.error(error.message)
    return Promise.reject(new Error(error))
  }
)

export default service
